package com.kevin.mapping.script.lexer;

public class Path {
    private boolean array;
    private String path;
    private Integer startIndex;
    private Integer endIndex;

    public static Path[] parser(String content) {
        String[] list = content.split("\\.");
        Path[] ret = new Path[list.length];
        int index = 0;
        for (String str : list) {
            Path valuePath = new Path();
            ret[index++] = valuePath;
            int startIndex = str.indexOf('[');
            int lastIndexOf = str.lastIndexOf(']');
            if (lastIndexOf == -1) {
                valuePath.setPath(str);
                continue;
            }
            String range = str.substring(startIndex + 1, lastIndexOf);
            if ("i".equals(range)) {
                valuePath.setArray(true);
            } else if (range.indexOf('-') > -1) {
                valuePath.setArray(true);
                valuePath.setStartIndex(Integer.parseInt(range.substring(0, range.indexOf('-')), 10));
                valuePath.setEndIndex(Integer.parseInt(range.substring(range.indexOf('-')), 10));
            } else {
                valuePath.setArray(true);
                valuePath.setStartIndex(Integer.parseInt(range));
                valuePath.setEndIndex(valuePath.getStartIndex() + 1);
            }

            valuePath.setPath(str.substring(0, startIndex));

        }
        return ret;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public Integer getStartIndex() {
        return startIndex;
    }

    public void setStartIndex(Integer startIndex) {
        this.startIndex = startIndex;
    }

    public Integer getEndIndex() {
        return endIndex;
    }

    public void setEndIndex(Integer endIndex) {
        this.endIndex = endIndex;
    }

    @Override
    public String toString() {
        StringBuilder ret = new StringBuilder(path);

        if (startIndex != null && startIndex > 0) {
            ret.append("[").append(startIndex);
        }
        if (endIndex != null && endIndex > 0 && !endIndex.equals(startIndex)) {
            ret.append("-").append(startIndex).append(']');
        }
        return ret.toString();
    }

    public boolean isArray() {
        return array;
    }

    public void setArray(boolean array) {
        this.array = array;
    }
}
